<template>
  <div class="parameter-value-display">
    <div class="card bg-base-100 shadow-md parameter-card" ref="paramterValueRef" :style="{ height: getParameterCardHeight() }">
      <div class="card-body p-4">
        <h2 class="card-title text-base">参数值</h2>
        <div class="keyboard-hint text-sm text-gray-500">
          提示: 单击参数名显示对应y轴；双击参数名或数值高亮显示对应曲线；右键点击参数名移除该参数
        </div>
        <div class="overflow-x-auto">
          <table class="table table-xs w-full">
            <thead>
              <tr class="table-header">
                <th>参数</th>
                <th v-if="activeChannels.includes('leftA')" class="text-center">左发A</th>
                <th v-if="activeChannels.includes('leftB')" class="text-center">左发B</th>
                <th v-if="activeChannels.includes('rightA')" class="text-center">右发A</th>
                <th v-if="activeChannels.includes('rightB')" class="text-center">右发B</th>
                <th v-if="activeChannels.includes('RJ')" class="text-center">值</th>
              </tr>
            </thead>
            <tbody class="table-content">
              <tr v-for="record in parameterValues" :key="record.key">
                <td
                  style="color: var(--text-color)"
                  class="cursor-pointer"
                  @click="emit('showParameterYAxis', record.key)"
                  @dblclick="highlightAllChannelsTemporarily(record.key)"
                  @contextmenu.prevent="removeParameter(record.key)"
                >
                  {{ getShowName(record.name) }}
                </td>
                <td v-if="activeChannels.includes('leftA')" class="text-center">
                  <span
                    :style="{ color: record.colors.leftA }"
                    @click="addToMeasureList(record.key, 'leftA')"
                    @dblclick="highlightLineTemporarily(record.key, 'leftA')"
                    class="cursor-pointer whitespace-nowrap inline-block"
                  >
                    <!-- <span v-if="record.paramType === 'discrete'"
                          :class="[
                            'badge badge-sm whitespace-nowrap',
                            record.leftA === '正常' ? 'badge-success' : 'badge-error'
                          ]">
                      {{ record.leftA }}
                    </span> -->
                    <span class="whitespace-nowrap">{{ record.leftA }}</span>
                  </span>
                </td>
                <td v-if="activeChannels.includes('leftB')" class="text-center">
                  <span
                    :style="{ color: record.colors.leftB }"
                    @click="addToMeasureList(record.key, 'leftB')"
                    @dblclick="highlightLineTemporarily(record.key, 'leftB')"
                    class="cursor-pointer whitespace-nowrap inline-block"
                  >
                    <!-- <span v-if="record.paramType === 'discrete'"
                          :class="[
                            'badge badge-sm whitespace-nowrap',
                            record.leftB === '正常' ? 'badge-success' : 'badge-error'
                          ]">
                      {{ record.leftB }}
                    </span> -->
                    <span class="whitespace-nowrap">{{ record.leftB }}</span>
                  </span>
                </td>
                <td v-if="activeChannels.includes('rightA')" class="text-center">
                  <span
                    :style="{ color: record.colors.rightA }"
                    @click="addToMeasureList(record.key, 'rightA')"
                    @dblclick="highlightLineTemporarily(record.key, 'rightA')"
                    class="cursor-pointer whitespace-nowrap inline-block"
                  >
                    <!-- <span v-if="record.paramType === 'discrete'"
                          :class="[
                            'badge badge-sm whitespace-nowrap',
                            record.rightA === '正常' ? 'badge-success' : 'badge-error'
                          ]">
                      {{ record.rightA }}
                    </span> -->
                    <span class="whitespace-nowrap">{{ record.rightA }}</span>
                  </span>
                </td>
                <td v-if="activeChannels.includes('rightB')" class="text-center">
                  <span
                    :style="{ color: record.colors.rightB }"
                    @click="addToMeasureList(record.key, 'rightB')"
                    @dblclick="highlightLineTemporarily(record.key, 'rightB')"
                    class="cursor-pointer whitespace-nowrap inline-block"
                  >
                    <!-- <span v-if="record.paramType === 'discrete'"
                          :class="[
                            'badge badge-sm whitespace-nowrap',
                            record.rightB === '正常' ? 'badge-success' : 'badge-error'
                          ]">
                      {{ record.rightB }}
                    </span> -->
                    <span class="whitespace-nowrap">{{ record.rightB }}</span>
                  </span>
                </td>
                <td v-if="activeChannels.includes('RJ')" class="text-center">
                  <span
                    :style="{ color: record.colors.RJ }"
                    @click="addToMeasureList(record.key, 'RJ')"
                    @dblclick="highlightLineTemporarily(record.key, 'RJ')"
                    class="cursor-pointer whitespace-nowrap inline-block"
                  >
                    <span class="whitespace-nowrap">{{ record.RJ }}</span>
                  </span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <div v-if="isMeasuring" class="card bg-base-100 shadow-md measurement-card" ref="measurementRef" :style="{ height: getMeasurementCardHeight() }">
      <div class="card-body p-4">
        <h2 class="card-title text-base">测量结果</h2>
        <div class="measurement-info flex gap-2">
          <!-- <span>游标1: {{ measurementData?.cursor1?.toFixed(2) }}</span>
          <span>游标2: {{ measurementData?.cursor2?.toFixed(2) }}</span> -->
          <span>ΔTime: {{ measurementData?.deltaTime }}s</span>
        </div>
        <div class="overflow-x-auto measurement-table-container" ref="measurementTableRef" @scroll="checkOverflowedParams">
          <div v-if="props.isMeasurementLoading" class="measurement-loading-overlay">
            <div class="measurement-loading-spinner"></div>
          </div>
          <table class="table table-xs">
            <thead>
              <tr class="table-header">
                <th v-for="col in statisticsColumns" :key="col.key">{{ col.title }}</th>
              </tr>
            </thead>
            <tbody class="table-content">
              <tr v-for="record in filteredStatisticsData" :key="record.key" :data-param-key="`${record.originalParamId}:${record.channelId}`">
                <td
                  @dblclick="removeFromMeasureList(record.originalParamId, record.channelId)"
                  class="cursor-pointer"
                  title="双击移除"
                  :style="{ color: record.color }"
                >
                  {{ getShowName(record.parameterId) }}{{ getChannelName(record.channelId) }}
                </td>
                <td :style="{ color: record.color }">
                  {{ record.min }}
                </td>
                <td :style="{ color: record.color }">
                  {{ record.max }}
                </td>
                <td :style="{ color: record.color }">
                  {{ record.avg }}
                </td>
                <td :style="{ color: record.color }">
                  {{ record.fluctuation }}
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- 故障列表模块 -->
    <div v-if="isFaultModeActive" class="card bg-base-100 shadow-md fault-card"
        ref="faultRef"
        :style="{ height: getFaultCardHeight() }">
      <div class="card-body p-4">
        <div class="flex justify-between items-center">
          <h2 class="card-title text-base">故障列表</h2>
          <div class="flex items-center gap-2">
            <button class="fault-settings-btn" @click="toggleFaultSettings" title="故障显示设置">
              <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <circle cx="12" cy="12" r="3"></circle>
                <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path>
              </svg>
            </button>
            <button class="close-fault-btn" @click="closeFaultMode" title="关闭故障列表">
              <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <line x1="18" y1="6" x2="6" y2="18"></line>
                <line x1="6" y1="6" x2="18" y2="18"></line>
              </svg>
            </button>
          </div>
        </div>
        <div class="keyboard-hint text-sm text-gray-500">
          <!-- 提示: 选择参数绘图后才能显示故障 -->
        </div>
        
        <!-- 故障显示设置面板 -->
        <div v-if="showFaultSettings" class="fault-settings-overlay" @click="cancelFaultSettings">
          <div class="fault-settings-modal modal-main" @click.stop>
            <div class="fault-settings-header modal-header">
              <h3 class="fault-settings-title">故障显示设置</h3>
            </div>
            <div class="fault-settings-content">
              <div class="settings-options">
                <label class="settings-option">
                  <input 
                    type="radio" 
                    v-model="tempFaultDisplayMode" 
                    value="line"
                    class="settings-radio"
                  />
                  <span>故障线显示</span>
                </label>
                <label class="settings-option">
                  <input 
                    type="radio" 
                    v-model="tempFaultDisplayMode" 
                    value="band"
                    class="settings-radio"
                  />
                  <span>色带显示</span>
                </label>
                <label class="settings-option">
                  <input 
                    type="radio" 
                    v-model="tempFaultDisplayMode" 
                    value="both"
                    class="settings-radio"
                  />
                  <span>同时显示</span>
                </label>
              </div>
            </div>
            <div class="fault-settings-footer modal-footer">
              <button class="tech-btn-warn import-btn-cancel" @click="cancelFaultSettings">取消</button>
              <button class="tech-btn import-btn-primary" @click="confirmFaultSettings">确定</button>
            </div>
          </div>
        </div>
        
        <!-- 故障检索功能 -->
        <div class="fault-search-section">
          <div class="search-row">
            <!-- <div class="search-field">
              <label class="search-label">通道号:</label>
              <select v-model="selectedChannel" class="search-select">
                <option value="">全部通道</option>
                <option v-for="channel in uniqueChannels" :key="channel" :value="channel">
                  {{ getChannelDisplayName(channel) }}
                </option>
              </select>
            </div> -->
            <div class="search-field">
              <label class="search-label">故障名称:</label>
              <input 
                v-model="searchFaultName" 
                placeholder="输入故障名称进行搜索"
                class="search-input"
              />
            </div>
          </div>
        </div>
        
        <div class="overflow-x-auto">
          <div v-if="!faultList || faultList.length === 0" class="no-fault-message">
            暂无故障数据
          </div>
          <div v-else class="fault-list">
            <div v-for="fault in filteredFaults" :key="fault.id" class="fault-item">
              <label class="fault-checkbox-label">
                <input 
                  type="checkbox" 
                  v-model="selectedFaults" 
                  :value="fault.id"
                  @change="handleFaultSelection"
                  class="fault-checkbox"
                />
                <div class="fault-info">
                  <div class="fault-name-details">
                    <span class="fault-name">{{ fault.name }}</span>
                    <span class="fault-details">{{ fault.occurrences.length }} 次</span>
                  </div>
                </div>
              </label>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 删除确认对话框 -->
  <div v-if="showDeleteConfirm" class="delete-confirm-overlay" @click="cancelDeleteParameter" ref="deleteConfirmRef">
    <div class="delete-confirm-modal" @click.stop>
      <div class="delete-confirm-header">
        <h3 class="delete-confirm-title">确认删除</h3>
      </div>
      <div class="delete-confirm-content">
        <p>确定要删除参数 "{{ deleteTargetParamName }}" 吗？</p>
        <p class="delete-warning">此操作将从当前选择中移除该参数。</p>
      </div>
      <div class="delete-confirm-footer">
        <button class="tech-btn" @click="cancelDeleteParameter">取消</button>
        <button class="tech-btn tech-btn-warn" @click="confirmDeleteParameter">确认删除</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, nextTick } from 'vue'
import type { ViewSettings } from '../../types'

// 定义参数数据接口
interface ParamsData {
  parameterId: string
  channelId: string
  value: string | number
  timestamp: number
  color?: string
}

const props = defineProps<{
  selectedParameters?: string[]
  selectedParametersList?: string[]
  selectedParametersInfo?: { id: string, name: string, type: string }[]
  cursorPosition?: number
  cursorData?: Record<string, Record<string, { value: number, timestamp: number, color: string }>>
  measurementData?: {
    cursor1: number,
    cursor2: number,
    deltaTime: number,
    measurementResults: Record<string, {
      parameterId: string,
      channelId: string,
      min: number,
      max: number,
      avg: number,
      fluctuation: number
    }>
  }
  viewSettings?: ViewSettings
  isFaultModeActive: boolean
  faultList?: { id: string, name: string, occurrences: { startTime: number }[], channelId: string }[]
  isMeasurementLoading?: boolean
}>()

// 添加emit用于通知父组件
const emit = defineEmits<{
  (e: 'showParameterYAxis', paramId: string): void
  (e: 'highlightLine', paramId: string, channelId: string): void
  (e: 'highlightAllChannels', paramId: string): void
  (e: 'removeParameter', paramId: string): void
  (e: 'toggle-fault-mode', value: boolean): void
  (e: 'fault-selected', faultIds: string[]): void
  (e: 'fault-display-mode-changed', mode: string): void
}>()
const flag = localStorage.getItem('flag')
// 测量相关状态
const paramsData = ref<ParamsData[]>([])
const isMeasuring = ref(false)
const measureParamList = ref<string[]>([]) // 存储用户选择测量的参数和通道
const overflowedParams = ref<Set<string>>(new Set()) // 记录溢出的参数（格式：paramId:channelId）
const hasManuallyInitialized = ref(false) // 标记是否已经手动初始化过测量列表

// 监听 measureParamList 变化，传递给父组件
watch(measureParamList, (newList) => {
  emit('update:measureParamList', newList)
}, { deep: true })

// 监听测量数据变化，当测量开始时自动添加所有已选择的参数
watch(() => props.measurementData, (newData, oldData) => {
  if (newData && Object.keys(newData.measurementResults).length > 0) {
    // 点开测量时，自动添加所有左侧已选择的参数
    if (!hasManuallyInitialized.value && props.selectedParameters && props.cursorData) {
      const newList: string[] = []
      for (const paramId of props.selectedParameters) {
        for (const channelId of Object.keys(props.cursorData)) {
          // 检查该通道下是否有该参数
          if (props.cursorData[channelId] && props.cursorData[channelId][paramId] !== undefined) {
            const key = `${paramId}:${channelId}`
            // 排除已经溢出过的参数
            if (!overflowedParams.value.has(key)) {
              newList.push(key)
            }
          }
        }
      }
      measureParamList.value = newList
      hasManuallyInitialized.value = true
    }
  } else if (!newData) {
    // 关闭测量时，重置标记
    hasManuallyInitialized.value = false
  }
}, { immediate: true, deep: true })

// 监听参数和游标数据变化，用于检测新增参数
watch(
  [() => props.selectedParameters, () => props.cursorData],
  ([selectedParameters, cursorData]) => {
    // 如果已经手动初始化过，则只处理新增的参数（排除溢出参数）
    if (hasManuallyInitialized.value && selectedParameters && cursorData) {
      const currentKeys = new Set(measureParamList.value)
      for (const paramId of selectedParameters) {
        for (const channelId of Object.keys(cursorData)) {
          // 检查该通道下是否有该参数
          if (cursorData[channelId] && cursorData[channelId][paramId] !== undefined) {
            const key = `${paramId}:${channelId}`
            // 如果是新参数且不在溢出列表中，则添加到测量列表
            if (!currentKeys.has(key) && !overflowedParams.value.has(key)) {
              measureParamList.value.push(key)
            }
          }
        }
      }
    }
  },
  { immediate: true, deep: true }
)

const paramterValueRef = ref<HTMLElement | null>(null)
const measurementRef = ref<HTMLElement | null>(null)
const deleteConfirmRef = ref<HTMLElement | null>(null)
const measurementTableRef = ref<HTMLElement | null>(null) // 测量结果表格的引用

// 统计数据表格列
const statisticsColumns = [
  {
    title: '参数',
    dataIndex: 'parameterId',
    key: 'parameterId',
  },
  // {
  //   title: '通道',
  //   dataIndex: 'channelId',
  //   key: 'channelId',
  // },
  {
    title: '最小值',
    dataIndex: 'min',
    key: 'min',
  },
  {
    title: '最大值',
    dataIndex: 'max',
    key: 'max',
  },
  {
    title: '平均值',
    dataIndex: 'avg',
    key: 'avg',
  },
  {
    title:'波动量',
    dataIndex: 'fluctuation',
    key: 'fluctuation',
  }
]

const getChannelName = (channel: string): string => {
  if (channel == 'leftA') return '-左发A'
  if (channel == 'leftB') return '-左发B'
  if (channel == 'rightA') return '-右发A'
  if (channel == 'rightB') return '-右发B'
  if (channel == 'RJ') return ''
  return channel // 确保函数总是有返回值
}

// 获取通道显示名称（用于故障列表）
const getChannelDisplayName = (channel: string): string => {
  if (channel == 'leftA') return '左发A'
  if (channel == 'leftB') return '左发B'
  if (channel == 'rightA') return '右发A'
  if (channel == 'rightB') return '右发B'
  if (channel == 'RJ') return 'RJ'
  return channel
}

// 获取参数名称 - 从parameters列表中获取
const getParameterName = (paramId: string): string => {
  // 从参数列表中查找
  const param = props.selectedParametersInfo?.find(p => p.id === paramId)
  if (param) {
    return param.name
  }

  // 如果找不到，直接返回参数ID
  return paramId
}

//去除虚拟参数前缀
const getShowName = (paramName: string): string => {
  if (paramName.startsWith('V_')) {
    return paramName.substring(2) // 去除"V_"前缀
  }
  return paramName
}

// 判断参数是否为离散类型
const isDiscreteParameter = (paramId: string): boolean => {
  // 从参数列表中查找
  const parameter = props.selectedParametersInfo?.find(p => p.id === paramId)
  if (parameter) {
    return parameter.displayType === 'discrete'
  }
  // 如果找不到参数信息，则默认为连续量类型
  return false
}

// 检查通道是否存在数据
const hasChannelData = (channelId: string): boolean => {
  if (!props.cursorData) return false

  // 检查此通道是否存在任何数据
  return !!props.cursorData[channelId] &&
        Object.keys(props.cursorData[channelId]).length > 0
}

// 获取有数据的通道列表
const activeChannels = computed(() => {
  return ['leftA', 'leftB', 'rightA', 'rightB', 'RJ'].filter(channelId =>
    hasChannelData(channelId)
  )
})

// 更新测量值 - 使用游标数据
const updateMeasurements = () => {
  if (!props.cursorData) {
    console.log('No cursor data available')
    return
  }

  const selectedParams = props.selectedParametersList || []
  const newParamsData: ParamsData[] = []

  // 对于每个选定的参数
  for (const paramId of selectedParams) {
    // 判断参数类型
    const paramType = isDiscreteParameter(paramId) ? 'discrete' : 'continuous'

    // 对于每个通道
    for (const channelId in props.cursorData) {

      const paramDataPoint = props.cursorData[channelId]?.[paramId]
      if (!paramDataPoint) {
        continue
      }

      // 获取值
      const value = paramDataPoint.value

      // 特殊处理不同类型的参数值格式化
      let formattedValue: string | number;
      if (paramId === 'RecTime') {
        // RecTime参数在RJ模式下是时间戳需要转换成日期格式，在非RJ模式下是秒数
        // 处理各种可能的时间格式
        let dateObj: Date;

        if (value && typeof value === 'object' && (value as any).getTime) {
          // 如果已经是Date对象（通过检查getTime方法）
          dateObj = value as Date;
        } else if (typeof value === 'number') {
          // 判断是秒时间戳还是毫秒时间戳
          // 如果数字小于10000000000（大约是2001年的毫秒时间戳），则认为是秒时间戳
          if (value < 10000000000) {
            // 秒时间戳，需要转换为毫秒
            dateObj = new Date(value * 1000);
          } else {
            // 毫秒时间戳
            dateObj = new Date(value);
          }
        } else if (typeof value === 'string') {
          // 如果是时间字符串，直接解析
          dateObj = new Date(value);
        } else {
          // 其他情况，使用当前时间
          dateObj = new Date();
        }
        
        // 检查Date是否有效
        if (isNaN(dateObj.getTime())) {
          formattedValue = '无效时间';
        } else {
          // 格式化为可读的时间字符串
          formattedValue = dateObj.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
          });
        }
        
      } else if (paramType === 'discrete') {
        // 离散参数显示为整数
        formattedValue = typeof value === 'number' ? value.toFixed(0) : value;
      } else {
        // 连续参数显示为小数
        formattedValue = typeof value === 'number' ? value.toFixed(3) : value;
      }

      newParamsData.push({
        parameterId: paramId,
        channelId,
        value: formattedValue,
        timestamp: paramDataPoint.timestamp,
        color: paramDataPoint.color as string // 使用类型断言
      })
    }
  }

  paramsData.value = newParamsData
}

// 添加到测量列表
const addToMeasureList = (paramId: string, channelId: string) => {
  if (!isMeasuring.value) {
    return
  }
  const key = `${paramId}:${channelId}`
  if (!measureParamList.value.includes(key)) {
    measureParamList.value.push(key)
  }
}

// 从测量列表中移除
const removeFromMeasureList = (paramId: string, channelId: string) => {
  const key = `${paramId}:${channelId}`
  measureParamList.value = measureParamList.value.filter(k => k !== key)
  // 将移除的参数标记为溢出，这样下次新增参数时也不会自动添加它
  overflowedParams.value.add(key)
}

// 检测溢出参数（在可视区域之外的参数）
const checkOverflowedParams = () => {
  if (!measurementTableRef.value) return
  
  const container = measurementTableRef.value
  const scrollTop = container.scrollTop
  const scrollBottom = scrollTop + container.clientHeight
  
  // 获取所有表格行
  const rows = container.querySelectorAll('tbody tr')
  rows.forEach((row) => {
    const paramKey = (row as HTMLElement).dataset.paramKey
    if (!paramKey) return
    
    // 计算行相对于容器的位置
    const rowTop = (row as HTMLElement).offsetTop
    const rowBottom = rowTop + (row as HTMLElement).offsetHeight
    
    // 如果行完全在可视区域之外，标记为溢出
    if (rowBottom < scrollTop || rowTop > scrollBottom) {
      overflowedParams.value.add(paramKey)
    }
  })
}
// 监听游标位置变化和游标数据变化
watch([() => props.cursorPosition, () => props.cursorData], () => {
  updateMeasurements()
}, { immediate: true, deep: true })

// 监听测量数据变化
watch(() => props.measurementData, (newData) => {
  if (newData && Object.keys(newData.measurementResults).length > 0) {
    // 移除自动添加参数到测量列表的代码，保持测量列表默认为空
    // 让用户通过点击参数值表格中的数据来添加到测量列表
  } else {
    console.log('No measurement data received')
  }
}, { immediate: true, deep: true })

// 确保在组件挂载时初始化数据
onMounted(() => {
  updateMeasurements()
})

// 格式化显示的参数值
const parameterValues = computed(() => {
  const result: any[] = []

  // 对于每个选定的参数
  for (const paramId of props.selectedParametersList || []) {
    // 判断参数类型
    const paramType = isDiscreteParameter(paramId) ? 'discrete' : 'continuous'

    // 创建一个新的结果行
    const row: any = {
      key: paramId,
      name: getParameterName(paramId),
      paramType,
      // 初始化所有可能的通道值为'-'
      leftA: '-',
      leftB: '-',
      rightA: '-',
      rightB: '-',
      RJ: '-',
      // 初始化通道颜色对象
      colors: {
        leftA: '',
        leftB: '',
        rightA: '',
        rightB: '',
        RJ: ''
      }
    }

    // 对于每个通道，查找该参数的值并赋值到正确的列
    for (const data of paramsData.value) {
      if (data.parameterId === paramId) {
        // 确保通道ID和表格列名完全匹配
        const channelId = data.channelId;
        if (channelId === 'leftA' || channelId === 'leftB' || channelId === 'rightA' || channelId === 'rightB' || channelId === 'RJ') {
          row[channelId] = data.value;
          // 保存颜色信息
          if (data.color) {
            row.colors[channelId] = data.color;
          }
        }
      }
    }

    result.push(row)
  }

  return result
})

// 处理测量统计数据
const statisticsData = computed(() => {
  if (!props.measurementData) return []

  const results = props.measurementData.measurementResults
  const data = Object.values(results).map(item => {
    // 解析原始参数ID和显示参数ID

    let paramId: string
    let displayId: string

    paramId = item.parameterId
    displayId = item.parameterId

    // 从cursorData中获取该参数该通道的颜色
    let color = '';
    if (props.cursorData && props.cursorData[item.channelId] && props.cursorData[item.channelId][paramId]) {
      color = props.cursorData[item.channelId][paramId].color;
    }

    return {
      key: `${paramId}-${item.channelId}`,  // 添加key属性确保唯一性
      parameterId: displayId || item.parameterId,
      originalParamId: paramId,
      parameterName: getParameterName(paramId),
      channelId: item.channelId,
      min: item.min.toFixed(3),
      max: item.max.toFixed(3),
      avg: item.avg.toFixed(3),
      fluctuation: item.fluctuation.toFixed(3),
      color: color  // 使用传递过来的颜色或计算得到的颜色
    }
  })

  return data
})

// 过滤统计数据只显示用户选中的参数和通道
const filteredStatisticsData = computed(() => {
  return statisticsData.value.filter(item => {
    const key = `${item.originalParamId}:${item.channelId}`
    return measureParamList.value.includes(key)
  })
})
// 高亮显示线条
const highlightLineTemporarily = (paramId: string, channelId: string) => {
  // 发送事件到父组件，通知需要高亮显示指定的线条
  emit('highlightLine', paramId, channelId)
}

// 高亮显示某个参数的所有通道曲线
const highlightAllChannelsTemporarily = (paramId: string) => {
  // 发送事件到父组件，通知需要高亮显示该参数的所有通道曲线
  emit('highlightAllChannels', paramId)
}

// 删除确认对话框相关状态
const showDeleteConfirm = ref(false)
const deleteTargetParam = ref<string>('')
const deleteTargetParamName = ref<string>('')

// 右键删除参数
const removeParameter = (paramId: string) => {
  // 获取参数名称用于确认对话框
  const paramName = getParameterName(paramId)
  deleteTargetParam.value = paramId
  deleteTargetParamName.value = paramName
  showDeleteConfirm.value = true
}

// 确认删除参数
const confirmDeleteParameter = () => {
  if (deleteTargetParam.value) {
    // 发送删除事件到父组件
    emit('removeParameter', deleteTargetParam.value)
    showDeleteConfirm.value = false
    deleteTargetParam.value = ''
    deleteTargetParamName.value = ''
  }
}

// 取消删除
const cancelDeleteParameter = () => {
  showDeleteConfirm.value = false
  deleteTargetParam.value = ''
  deleteTargetParamName.value = ''
}

// 故障列表相关状态
const faultRef = ref<HTMLElement | null>(null)
const selectedFaults = ref<string[]>([])

// 监听故障模式激活状态，当激活且有故障数据时自动选择所有故障
watch(
  () => props.isFaultModeActive,
  (isActive) => {
    if (isActive && props.faultList && props.faultList.length > 0) {
      // 当故障模式激活且有故障数据时，自动选择所有故障
      selectedFaults.value = props.faultList.map(fault => fault.id)
      // 通知父组件故障选择变化
      emit('fault-selected', selectedFaults.value)
    }
  },
  { immediate: true }
)

// 监听故障列表变化，当故障列表更新时重新选择所有故障
watch(
  () => props.faultList,
  (newFaultList) => {
    if (props.isFaultModeActive && newFaultList && newFaultList.length > 0) {
      // 当故障模式激活且故障列表有数据时，自动选择所有故障
      selectedFaults.value = newFaultList.map(fault => fault.id)
      // 通知父组件故障选择变化
      emit('fault-selected', selectedFaults.value)
    }
  },
  { immediate: true }
)

// 处理故障选择
const handleFaultSelection = () => {
  emit('fault-selected', selectedFaults.value)
}

// 格式化时间
const formatTime = (timestamp: number) => {
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 关闭故障模式
const closeFaultMode = () => {
  emit('toggle-fault-mode', false)
}

// 获取参数卡片高度
const getParameterCardHeight = () => {
  if (!props.isFaultModeActive && !isMeasuring.value) {
    return '100%' // 只有参数值卡片时占满高度
  } else if (props.isFaultModeActive && !isMeasuring.value) {
    return '50%' // 参数值和故障列表平均分配
  } else if (!props.isFaultModeActive && isMeasuring.value) {
    return '50%' // 原有逻辑，参数值卡片自适应
  } else {
    return '33.33%' // 三个模块平均分配
  }
}

// 获取测量卡片高度
const getMeasurementCardHeight = () => {
  if (props.isFaultModeActive) {
    return '33.33%' // 三个模块平均分配
  } else {
    return '50%' // 原有逻辑，测量卡片自适应（flex: 1）
  }
}

// 获取故障卡片高度
const getFaultCardHeight = () => {
  if (isMeasuring.value) {
    return '33.33%' // 三个模块平均分配
  } else {
    return '50%' // 参数值和故障列表平均分配
  }
}

// 故障显示设置相关状态
const showFaultSettings = ref(false)
const faultDisplayMode = ref('line')
const tempFaultDisplayMode = ref('line')

// 切换故障显示设置
const toggleFaultSettings = () => {
  tempFaultDisplayMode.value = faultDisplayMode.value // 同步当前值到临时变量
  showFaultSettings.value = !showFaultSettings.value
}

// 处理故障显示模式变化
const confirmFaultSettings = () => {
  faultDisplayMode.value = tempFaultDisplayMode.value // 保存临时值到正式变量
  emit('fault-display-mode-changed', faultDisplayMode.value)
  showFaultSettings.value = false
}

// 取消故障设置
const cancelFaultSettings = () => {
  tempFaultDisplayMode.value = faultDisplayMode.value // 恢复临时值为当前值
  showFaultSettings.value = false
}

// 故障检索相关状态
const selectedChannel = ref('')
const searchFaultName = ref('')
const uniqueChannels = computed(() => {
  return Array.from(new Set(props.faultList?.map(f => f.channelId) || []))
})
const filteredFaults = computed(() => {
  if (!props.faultList) return []
  return props.faultList.filter(f => {
    const matchesChannel = selectedChannel.value === '' || f.channelId === selectedChannel.value
    const matchesName = searchFaultName.value === '' || f.name.includes(searchFaultName.value)
    return matchesChannel && matchesName
  })
})

// 清空选择故障
const clearSelectedFault = () => {
  selectedFaults.value = []
  selectedChannel.value = ''
  searchFaultName.value = ''
  // 通知父组件故障选择变化
  // emit('fault-selected', selectedFaults.value)
}

// 手动选择所有故障
const selectAllFaults = () => {
  if (props.faultList && props.faultList.length > 0) {
    selectedFaults.value = props.faultList.map(fault => fault.id)
    // 通知父组件故障选择变化
    emit('fault-selected', selectedFaults.value)
  }
}

const updateIsMeasuring = (value: boolean) => {
  isMeasuring.value = value;
}

defineExpose({clearSelectedFault,updateIsMeasuring})
</script>

<style scoped>
@import '../../../src/assets/css/theme.css';
@import '../../../src/assets/css/buttons.css';
@import '../../../src/assets/css/modal.css';
*{
  -webkit-touch-callout:none; /*系统默认菜单被禁用*/
  -webkit-user-select:none; /*webkit浏览器*/
  -khtml-user-select:none; /*早期浏览器*/
  -moz-user-select:none;/*火狐*/
  -ms-user-select:none; /*IE10*/
  user-select:none; 
}
.parameter-value-display {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 16px;
  overflow: hidden;
}

.card {
  background: var(--sub-plate-bg-color);
  border-radius: 8px;
  /*border: 1px solid rgba(30, 64, 175, 0.1);*/
  border: 1px solid var(--modal-main-border-color) !important;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  position: relative;
}

.card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: var(--sub-plate-bg-color);
}

.card-body {
  color: var(--text-color);
  background: var(--sub-plate-bg-color);
  padding: 16px;
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.card-title {
  /* margin-bottom: 10px; */
  flex-shrink: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color);
}

.overflow-x-auto {
  overflow: auto;
  flex: 1;
  min-height: 0;
}

.parameter-card {
  display: flex;
  flex-direction: column;
}

.measurement-card {
  display: flex;
  flex-direction: column;
  overflow-y: hidden;
}

.measurement-info {
  display: flex;
  justify-content: space-between;
  font-size: 15px;
  /* font-weight: bold; */
}

.table td {
  padding-left: 0.5rem;
  padding-right: 0.5rem;
}

.keyboard-hint {
  color: var(--preview-text-color);
  font-size: 13px;
  margin-top: 4px;
}

.table-header th {
    padding-top: 4px;
    padding-bottom: 4px;
    position: sticky;
    top: 0;
    color:var(--text-color);
    background: var(--table-header-bg-color);
    z-index: 1;
}

/* 1024*768分辨率适配 */
@media (max-width: 1024px) {
  .parameter-value-display {
    gap: 6px;
  }
  
  .card-body {
    padding: 8px;
    gap: 0;
  }
  
  .card-title {
    font-size: 12px;
    margin-bottom: 4px;
  }
  
  .table-header th {
    padding-top: 4px;
    padding-bottom: 4px;
    position: sticky;
    top: 0;
      color:var(--text-color);
    background: var(--table-header-bg-color);
    z-index: 1;
  }
  .fault-settings-modal{
      max-width: 100%;
  }
  .table-content td {
    padding: 2px;
  }
  
  .measurement-info {
    font-size: 11px;
    margin-bottom: 3px;
  }
  
  /* 表格文本强制单行显示，超出显示...省略号 */
  .table td {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100px;
  }
  
  /* 确保表格不会过宽 */
  .overflow-x-auto {
    overflow-x: auto;
    max-width: 100%;
  }
  
  /* 参数名称列宽度控制 */
  .table-content tr td:first-child {
    max-width: 80px;
  }

  .keyboard-hint {
    font-size: 10px;
    margin-top: 0px;
  }
}

/* 删除确认对话框样式 */
.delete-confirm-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.delete-confirm-modal {
  background: var(--se-main-bg-color);
  border-radius: 8px;
  padding: 0;
  min-width: 300px;
  max-width: 400px;
  /*box-shadow: 0 4px 12px var(--box-shadow);*/
  animation: modalSlideIn 0.2s ease-out;
}

.delete-confirm-header {
  padding: 16px 20px;
  border-radius: 8px 8px 0 0;
  background: var(--se-title-bg-color);
  border-bottom: 1px solid var(--modal-divide);
}

.delete-confirm-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color);
}

.delete-confirm-content {
  padding: 20px;
}

.delete-confirm-content p {
  margin: 0 0 8px 0;
  color: var(--text-color);
  line-height: 1.5;
}

.delete-warning {
  font-size: 14px;
  color: #666;
}

.delete-confirm-footer {
    border-radius: 0 0 8px 8px;
  padding: 16px 20px;
  border-top: 1px solid var(--modal-divide);
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}


@keyframes modalSlideIn {
  from {
    transform: scale(0.9);
    opacity: 0;
  }
  to {
    transform: scale(1);
    opacity: 1;
  }
}

/* 故障列表样式 */
.fault-card {
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.close-fault-btn, .fault-settings-btn {
  padding: 4px;
  border: none;
  color: var(--text-color);
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.2s;
}

.close-fault-btn:hover, .fault-settings-btn:hover {
  background: var(--btn-hover-color);
}

.no-fault-message {
  text-align: center;
  color: var(--preview-text-color);
  padding: 20px;
  font-size: 14px;
}

.fault-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.fault-item {
  transition: all 0.2s;
}

.fault-item:hover {
  border-color: var(--btn-border);
  background: var(--table-body-bg-color);
}

.fault-checkbox-label {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  cursor: pointer;
}

.fault-checkbox {
    border: 1px solid var(--btn-click-color);
    background-color: var(--ant-checkbox-inner);
    color: var(--global-color-white);
    appearance: none;
    -webkit-appearance: none;
    width: 16px !important;
    height: 16px !important;
    border-radius: 4px; /* 圆角 */
    outline: none;
    cursor: pointer;
    position: relative;
    transition: all 0.2s ease; /* 平滑过渡效果 */
}
.fault-checkbox:checked{
    color: var(--global-color-white);
    background-color: var(--ant-checkbox-checked);
    border-color: var(--btn-click-color);
}
.fault-checkbox:checked::after{
    content: "";
    position: absolute;
    left: 30%;
    top: 1px;
    width: 6px;
    height: 10px;
    border-width: 0 2px 2px 0;
    transform: rotate(45deg);
}
.fault-info {
  flex: 1;
}

.fault-name-details {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.fault-name {
  color: var(text-color);
  font-size: 14px;
}

.fault-details {
  font-size: 12px;
  color: var(--preview-text-color);
  flex-shrink: 0;
}

/* 故障显示设置面板样式 */
.fault-settings-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.fault-settings-modal {
  padding: 0;
  min-width: 300px;
  max-width: 400px;
  /*box-shadow: 0 4px 12px var(--box-shadow);*/
  animation: modalSlideIn 0.2s ease-out;
}

.fault-settings-header {
  padding: 16px 20px;
}

.fault-settings-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-color);;
}

.fault-settings-content {
    background: var(--se-main-bg-color);
  padding: 20px;
}

.fault-settings-footer {
  padding: 16px 20px;
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}
.import-btn-cancel, .import-btn-primary {
  height: 36px;
  font-size: 0.875rem;
  padding: 0.35rem 0.75rem;
  border-radius: 0.375rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.import-btn-primary {
  background: var(--btn-color);
  border: 1px solid var(--btn-border);
  color: var(--text-color);
}

.import-btn-primary:hover {
  background: var(--btn-hover-color);
  border-color: var(--btn-border);
  color: var(--text-color);
  transform: translateY(-1px);
  box-shadow: 0 2px 5px var(--box-shadow);
}

.import-btn-primary:disabled {
  background: var(--btn-disabled-color);
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.settings-options {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.settings-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

/*.settings-radio {*/
/*  margin-top: 2px;*/
/*  width: 16px;*/
/*  height: 16px;*/
/*  cursor: pointer;*/
/*}*/
.settings-radio {
    appearance: none;
    width: 16px;
    height: 16px;
    border-radius: 50%;
    border: 1px solid var(--border-color-base);
    outline: none;
    cursor: pointer;
    position: relative;
    transition: border-color 0.2s ease, background-color 0.2s ease, box-shadow 0.2s ease;
    will-change: transform, border-color, background-color, box-shadow;
    transform: translateZ(0);
    backface-visibility: hidden;
    vertical-align: middle;
    margin: 2px;
}

.settings-radio:checked {
    background-color: var(--ant-checkbox-checked);
    border: 1px solid var(--btn-click-color);
    box-shadow: var(--ant-checkbox-shadow);
}

.settings-radio:checked::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%) translateZ(0);
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background: var(--global-color-white);
    display: block;
}
@keyframes modalSlideIn {
  from {
    transform: scale(0.9);
    opacity: 0;
  }
  to {
    transform: scale(1);
    opacity: 1;
  }
}

/* 故障检索相关样式 */
.fault-search-section {
  margin-bottom: 8px;
}

.search-row {
  display: flex;
  gap: 16px;
}

.search-field {
  flex: 1;
}

.search-label {
  color: var(--text-color);
  display: block;
  margin-bottom: 4px;
  font-weight: 600;
  font-size: 14px;
}

.search-select,
.search-input {
    background: var(--select-background);
  color: var(--text-color);
  width: 100%;
  padding: 6px 8px;
  border: 1px solid var(--input-border-color);
  border-radius: 4px;
  font-size: 14px;
}

.search-select:focus,
.search-input:focus {
  outline: none;
  border: 1px solid var(--btn-hover-color);
}
.search-select option{
    background: var(--select-dropdown-bg);
    padding: 8px 12px;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
    color: var(--text-color);
    transition: all 0.2s ease;
    border-bottom: 1px solid var(--select-border-color);
}

.search-select option:last-child {
    border-bottom: none;
}

.search-select option:hover {
    background: var(--text-color);
    color: var(--select-dropdown-bg);
}

/* 测量表格loading样式 */
.measurement-table-container {
  position: relative;
}

.measurement-loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
  border-radius: 4px;
}

.measurement-loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-top: 3px solid #3498db;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
